package com.regis.service.impl;

import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.regis.comment.CodeMsg;
import com.regis.comment.GlobalException;
import com.regis.entity.db.User;
import com.regis.entity.ro.EmailRo;
import com.regis.entity.vo.ResultVo;
import com.regis.service.UserService;
import com.regis.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
* @author 纱雾休比酱
* @description 针对表【user(用户信息)】的数据库操作Service实现
* @createDate 2022-07-28 03:58:08
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${spring.mail.host}")
    private String host;
    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 发送邮箱
     * @param emailRo EmailRo
     */
    @Override
    public void send(EmailRo emailRo) {
        //设置
        MailAccount account = new MailAccount();
        account.setHost(host);
        // 设置发送人邮箱
        account.setFrom("瑞吉外卖用户登录服务" + "<" + username + ">");
        // 设置发送人名称
        account.setUser(username);
        // 设置发送授权码
        account.setPass(password);
        account.setAuth(true);
        // ssl方式发送
        account.setSslEnable(true);
        // 使用安全连接
        account.setStarttlsEnable(true);

        //发送邮件
        try {
            Mail.create(account)
                    .setTos(emailRo.getEmail())
                    .setTitle(emailRo.getSubject())
                    .setContent(emailRo.getContent())
                    .setHtml(true)
                    //关闭session
                    .setUseGlobalSession(false);
//                    .send();
            //将验证码保存到redis
            redisTemplate.opsForValue().set(emailRo.getEmail(), emailRo.getCode(),120, TimeUnit.SECONDS);
        } catch (Exception e){
            e.printStackTrace();
            throw new GlobalException(new CodeMsg("邮件发送失败"));
        }
    }

    /**
     * 用户登录
     */
    @Override
    public ResultVo<User> login(String email, String code) {
        //比对验证码
        Integer codeInRedis = (Integer) redisTemplate.opsForValue().get(email);
        if(codeInRedis != null && Objects.equals(code,codeInRedis.toString())){
            //判断当前登录用户是否为新用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,email);
            User user = this.getOne(queryWrapper);
            if(user == null){
                user = new User();
                user.setPhone(email);
                user.setStatus(1);
                user.setName("用户"+ IdWorker.getId()%100000000L);
                this.save(user);
            }
            //登录成功，删除缓存的验证码
            redisTemplate.delete(email);
            return ResultVo.success(user);
        }else if (codeInRedis != null && !Objects.equals(code,codeInRedis.toString())){
            return ResultVo.error("验证码错误");
        }
        return ResultVo.error("登录失败");
    }
}




